<template>
  <div class="main">
    <div class="topTitle">{{ props.title }}</div>
    <div class="form_content">
      <NScrollbar>
        <NSpin :show="spinShow">
          <div class="content">
            <NSpace>
              <div style="width: 500rem; display: flex; justify-content: center">
                <NForm ref="formRef" require-mark-placement="left" label-placement="left" :rules="rules"
                  :label-width="100" :model="formValue">
                  <NFormItem label="日期:" path="dutyDate">
                    <NDatePicker input-readonly placeholder="请选择日期" clearable class="commonWidth"
                      v-model:formatted-value="formValue.dutyDate" type="date" />
                  </NFormItem>
                  <NFormItem label="班次:" path="shift">
                    <NSelect :options="[
                      { label: '白班', value: 'day' },
                      { label: '夜班', value: 'night' }
                    ]" placeholder="请选择班次" clearable class="commonWidth" v-model:value="formValue.shift" />
                  </NFormItem>

                  <NSpace style="display: flex; flex-direction: column" v-if="!props.id">
                    <NFormItem label="发布范围:" path="users">
                      <div style="width: 100%">
                        <NButton style="width: 115px; margin-bottom: 10rem" type="primary" ghost @click="openScope">
                          选择同伴
                        </NButton>
                        <div style="width: 360rem;overflow: hidden;height: 120rem;background-color: #e1e1e1;
                     " v-if="formValue.users?.length">
                          <NScrollbar>
                            <div class="scope">
                              <div class="userBox" v-for="(item, index) in formValue.users" :key="index">
                                <div>{{ item.typeName }}</div>
                                <n-icon @click="handleScope(item.identifyingId)" style="cursor: pointer">
                                  <CloseFilled />
                                </n-icon>
                              </div>
                            </div>
                          </NScrollbar>
                        </div>
                      </div>
                    </NFormItem>
                  </NSpace>

                  <NSpace style="display: flex; flex-direction: column" v-else>
                    <NFormItem label="人员:" path="users">
                      <div style="width: 100%; background-color: #e1e1e1; padding: 10rem">
                        {{ userName }}
                      </div>
                    </NFormItem>
                  </NSpace>

                  <NFormItem label="备注:" path="remark">
                    <NInput placeholder="请输入备注" style="width: 100%; min-height: 200rem" type="textarea"
                      v-model:value="formValue.remark" clearable />
                  </NFormItem>
                </NForm>
              </div>
            </NSpace>
          </div>
        </NSpin>
      </NScrollbar>
    </div>
  </div>
  <FixedAction>
    <NSpace justify="center">
      <NButton ghost @click="goBack">
        取消
      </NButton>
      <NButton type="primary" @click="confirm" :loading="loading">
        提交申请
      </NButton>
    </NSpace>
  </FixedAction>

  <NModal :auto-focus="false" v-model:show="contentVisible" @close="contentVisible = false">
    <VDialogContent @close="contentVisible = false" @submit="submit" title="保存提示">
      <div style="width: 300rem; height: 100rem; text-align: center; line-height: 100rem">
        您确定要提交申请吗？
      </div>
    </VDialogContent>
  </NModal>

  <NModal :auto-focus="false" v-model:show="modalVisible" @close="modalVisible = false">
    <VScope @close="modalVisible = false" @scopeSubmit="getScopeList" :defaultList="scopeList" :flat="true" />
  </NModal>
</template>
<script setup lang="ts">
import { ref, reactive, watch } from 'vue'
import {
  NSpace,
  NForm,
  NInput,
  NFormItem,
  NSelect,
  NButton,
  NScrollbar,
  NModal,
  useMessage,
  NDatePicker,
  NSpin,
  NIcon,
  type FormInst
} from 'naive-ui'
import router from '@/router'
import { onMounted } from 'vue'
import { useTagStore } from '@/stores/layout'
import FixedAction from '@/components/FixedAction.vue'
import { sendRequest } from '@/utils/api'
import type { HttpResponse } from '@/utils/http'
import type { DutyModel } from '@/api/duty'
import { useRoute } from 'vue-router'
import VDialogContent from '@/views/OA/Common/DialogContent.vue'
import VScope from '@/views/OA/Common/Scope.vue'
import { CloseFilled } from '@vicons/material'

const tags = useTagStore().tags
const route = useRoute()
const props = defineProps({
  title: { type: String, default: () => '值班排版申请' },
  id: { type: [Number, String], default: () => null },
  flat: { default: () => false },
  dutyDate: { default: () => undefined }
})
const message = useMessage()

const formValue = reactive<Record<string, any>>({
  dutyDate: props.dutyDate, //时间
  remark: null, //备注
  shift: null //类型
})
const rules = {
  dutyDate: {
    required: true,
    message: '请选择时间',
    trigger: ['select', 'change']
  },
  shift: {
    required: true,
    message: '请选择班次',
    trigger: ['select', 'change']
  }
}
// 打开发布范围
const modalVisible = ref(false)
const scopeList = ref()
const openScope = () => {
  scopeList.value = formValue.users
  modalVisible.value = true
}
// 发布范围选择
const getScopeList = (v: any) => {
  formValue.users = v
  modalVisible.value = false
}
// 范围选择是删除
const handleScope = (id: any) => {
  const index = formValue.users.findIndex((it: any) => it.identifyingId == id)
  formValue.users.splice(index, 1)
}
// 返回
const goBack = () => {
  const index = tags.findIndex((item: any) => item.path === router.currentRoute.value.fullPath)

  tags.splice(index, 1)
  if (tags.length == 0) {
    router.push({ path: '/OA/Workbench/UserDesktop' })
  } else history.back()
}
// 确定
const loading = ref(false)
const formRef = ref<FormInst | null>(null)
const confirm = () => {
  formRef.value?.validate(async (err) => {
    if (err) return (contentVisible.value = false)
    contentVisible.value = true
  })
}
// 提交
const contentVisible = ref(false)
const submit = async () => {
  if (props.id && props.flat) {
    loading.value = true
    contentVisible.value = false
    const [error, res] = await sendRequest<HttpResponse<DutyModel>>({
      module: 'duty',
      api: 'workDutyUpdate',
      override: {
        data: {
          ...formValue,
          id: props.id
        }
      }
    })
    loading.value = false
    if (error) return message.error(error.message)
    if (res.code !== 0) return message.error(res.msg)
    message.success('保存成功')
  } else {
    loading.value = true
    contentVisible.value = false
    const [error, res] = await sendRequest<HttpResponse<DutyModel>>({
      module: 'duty',
      api: 'dutySave',
      override: {
        data: {
          ...formValue
        }
      }
    })
    loading.value = false
    if (error) return message.error(error.message)
    if (res.code !== 0) return message.error(res.msg)
    message.success('保存成功')
  }
  goSubmit()
}

//提交完跳转我的提交
const goSubmit = () => {
  const index = tags.findIndex((item: any) => item.path === router.currentRoute.value.fullPath)
 tags.splice(index, 1)
  if(formValue.draft) return router.push({ path: '/OA/UserCenter/Drafts' })
  router.push({ path: '/OA/UserCenter/Submit' })
}


// 获取修改详情
const userName = ref()
const spinShow = ref(false)
const getWorkDutyInfo = async () => {
  spinShow.value = true
  const [error, res] = await sendRequest<HttpResponse<DutyModel>>({
    module: 'duty',
    api: 'workDutyInfo',
    uri: {
      id: props.id
    }
  })
  spinShow.value = false
  if (error) return message.error(error.message)
  if (res.code !== 0) return message.error(res.msg)
  Object.keys(formValue).map((it: any) => {
    // @ts-ignore
    if (it == 'dutyDate') return (formValue[it] = res.data[it].split(' ')[0])
    // @ts-ignore
    formValue[it] = res.data[it]
  })
  userName.value = res.data.userName
}

watch(
  () => props.id,
  () => {
    if (props.title == '值班排版编辑' && props.id) getWorkDutyInfo()
  },
  { deep: true, immediate: true }
)
onMounted(async () => { })
</script>
<style scoped lang="scss">
@mixin CommonFont {
  font-size: 16rem;
  font-family: PingFangSC, PingFang SC;
  font-weight: 400;
  color: rgba(0, 0, 0, 0.85);
}

.commonWidth {
  width: 100%;
  min-width: 360rem;
}

.main {
  display: flex;
  flex-direction: column;
  width: 100%;
  height: 100%;
  overflow: hidden;

  .topTitle {
    width: 100%;
    border-bottom: 1px solid #fff;
    padding: 15rem 20rem;
    margin-bottom: 20rem;
    @include CommonFont;
  }

  .form_content {
    width: 100%;
    height: 100%;
    padding: 0 20rem 0rem;

    .content {
      display: flex;
      align-items: center;
      flex-direction: column;
      width: 100%;
      height: 100%;
      padding: 20rem 0 180rem;
      overflow-y: scroll;
      background-color: #ebeceb;

      .scope {
        display: flex;
        flex-wrap: wrap;
        width: 100%;

        .userBox {
          display: flex;
          justify-content: space-between;
          align-items: center;
          width: 100%;
          height: 40rem;
          background-color: #fff;
          border-radius: 4rem;
          padding: 5px 10rem;
          margin-bottom: 10rem;
        }
      }
    }
  }
}

.scope {
  display: flex;
  flex-wrap: wrap;
  width: 100%;
  height: auto;
  min-height: 130rem;
  background: #e1e1e1;
  padding: 15rem 20rem;

  .userBox {
    display: flex;
    justify-content: space-between;
    align-items: center;
    width: auto;
    min-width: 150rem;
    height: 40rem;
    background-color: #fff;
    border-radius: 4rem;
    padding: 0 10rem;
    margin-right: 20rem;
    margin-bottom: 10rem;
  }
}

.content::-webkit-scrollbar {
  display: none;
}

:deep(.n-spin-container) {
  width: 100%;
  height: 100%;
}

:deep(.n-scrollbar-container) {
  width: 100%;
  height: 100%;
}

:deep(.n-scrollbar-content) {
  width: 100%;
  height: 100%;
}

:deep(.n-spin-content) {
  width: 100%;
  height: 100%;
}
</style>
